package com.sita.bluetactivity.VehicleFragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentContainer;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseMapFragment;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Base.SpUtils;
import com.sita.bluetactivity.MainActivity;
import com.sita.bluetactivity.MineFragment.FindVehicleBtActivity;
import com.sita.bluetactivity.NewBlueTooth.BtService;
import com.sita.bluetactivity.NewBlueTooth.StopFindEvent;
import com.sita.bluetactivity.R;
import com.sita.bluetactivity.TripFragment.GpsCorrect;
import com.sita.bluetactivity.http.Constants;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static android.app.Activity.RESULT_CANCELED;
/**
 * Created by Jason on 2016/9/21.
 */
public class VehicleFragment extends Fragment implements View.OnClickListener{
    private MapView mapView;
    private ImageButton location;
    private View view;
    private TextView vehicleMsg;
    private ImageView vehicleStart,vehicleRemoval,vehicleRing;
    private AMap aMap;
    private UiSettings uiSetting;
    private Marker vehicleLocationMarker;
    private BtService.BtBinder myBinder;
    private static String newPass;
    private static String BoDaoID;
    private LatLng bodaolatLng;//定位坐标
    private  Gson gson = new Gson();
    private  VehicleToken token = new VehicleToken();
    private BoDaoLocation boDaoLocation= new BoDaoLocation();
    private static Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            getVehicleLocation();
            Log.e("VehicleLocation","定位车辆位置");
            handler.postDelayed(runnable,5000);
        }
    };
    private void startTime(){
        handler.post(runnable);
    }
    private void stopTime(){
        handler.removeCallbacks(runnable);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_vehicle,null);
        mapView = (MapView) view.findViewById(R.id.my_map);
        mapView.onCreate(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
        return view;
    }



    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            stopTime();
        }
        else {
            startTime();
            showVehicleLocation(bodaolatLng);
            newPass = SpUtils.getString("ConnectionPass",null,BaseApplication.getContext());

           if (SpUtils.getString("BoDaoID",null,BaseApplication.getContext())!=null){
               BoDaoID = SpUtils.getString("BoDaoID",null,BaseApplication.getContext());
           }
            else {
             //  BoDaoID = "011000876";
           }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initMap();
        initView();
        initData();

    }
    private void initMap(){
        if (aMap==null){
            aMap = mapView.getMap();
            setUpMap();
        }

    }
    private void setUpMap(){
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.setMyLocationEnabled(true);
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        uiSetting =   aMap.getUiSettings();
        uiSetting.setTiltGesturesEnabled(false);
        uiSetting.setZoomControlsEnabled(false);
    }
    private void initView(){
        location = (ImageButton) view.findViewById(R.id.my_location);
        vehicleStart = (ImageView) view.findViewById(R.id.vehicle_start_bt);
        vehicleRemoval = (ImageView) view.findViewById(R.id.vehicle_removal);
        vehicleRing = (ImageView) view.findViewById(R.id.vehicle_ring);
        vehicleMsg = (TextView) view.findViewById(R.id.location_msg);
        getStartBtState();
        getRemovalBtState();

    }
    private void    getStartBtState(){
        if (Constants.isStart){
            vehicleStart.setImageResource(R.mipmap.vehicle_end);
        }
        else {
            vehicleStart.setImageResource(R.mipmap.vehicle_start);
        }
    }
    private void getRemovalBtState(){

        if (Constants.isRemoval){
            vehicleRemoval.setImageResource(R.mipmap.removal_stlect);
        }
        else {
            vehicleRemoval.setImageResource(R.mipmap.removal);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onClick(View v) {
        //临时的逻辑


           switch (v.getId()){
               case R.id.my_location:
                   if (bodaolatLng!=null){
                       showVehicleLocation(bodaolatLng);
                   }
                   break;
               case R.id.vehicle_start_bt:
                   if (Constants.isStart){
                       Constants.isStart=false;
                       vehicleStart.setImageResource(R.mipmap.vehicle_start);
                       if (myBinder!=null){
                           myBinder.CommunicationWrite("18180D01"+newPass+"0000000D0A");//关闭
                       }
                   }
                   else {
                       Constants.isStart = true;
                       vehicleStart.setImageResource(R.mipmap.vehicle_end);
                       if (myBinder!=null){

                           myBinder.CommunicationWrite("18180D01"+newPass+"0100000D0A");//开启
                       }

                   }
                   break;
               case R.id.vehicle_removal:
                   //撤防   布防 ///黑
                   if (Constants.isRemoval){
                       Constants.isRemoval=false;
                       Constants.isStart = false;
                       vehicleRemoval.setImageResource(R.mipmap.removal);
                       vehicleStart.setImageResource(R.mipmap.vehicle_start);
                       if (myBinder!=null) {
                           myBinder.CommunicationWrite("18180D02"+newPass+"0100000D0A");//布防
                       }
                   }
                   else {
                       Constants.isRemoval = true;
                       Constants.isStart = false;
                       vehicleRemoval.setImageResource(R.mipmap.removal_stlect);
                       if (myBinder!=null) {
                           Log.e("sxxxxxxx","18180D02"+newPass+"0000000D0A");
                           myBinder.CommunicationWrite("18180D02"+newPass+"0000000D0A");//撤防

                       }
                   }
                   break;
               case R.id.vehicle_ring:
                   //响铃
                   if (myBinder!=null) {
                       myBinder.CommunicationWrite("18180D03"+newPass+"0100000D0A");
                   }
                   break;
           }
    }
    private void   showVehicleLocation(LatLng latLng){

        if (latLng!=null){
            aMap.moveCamera(CameraUpdateFactory.
                    newCameraPosition(new CameraPosition(latLng,15,0,0)));
        }

    }
    private void initData(){
        location.setOnClickListener(this);
        vehicleRemoval.setOnClickListener(this);
        vehicleRing.setOnClickListener(this);
        vehicleStart.setOnClickListener(this);

    }
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        stopTime();
        EventBus.getDefault().unregister(this);
    }
    private void showVehicle(LatLng latlng){

        if (vehicleLocationMarker == null) {
            //定位自己的位置
            Bitmap locationMe = BitmapFactory.decodeResource(
                    this.getResources(), R.mipmap.vehicle_location);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            vehicleLocationMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon)
                    .position(latlng).setFlat(true));

        } else {
            //设置marker 的经纬度位置。
            vehicleLocationMarker.setPosition(latlng);
        }

    }

    //MainActivity与服务绑定以后发送binder对象来
    public void onEventMainThread(BtService.BtBinder event) {
        myBinder = event;
    }

//蓝牙连接成功之后寻车
    public void onEventMainThread(StopFindEvent event) {

        if (event.getPass()!=null&&newPass!=null&&!event.getPass().equals("41414141")){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myBinder.CommunicationWrite("18180D03"+event.getPass()+"0100000D0A");
        }
    }

    private void getVehicleLocation(){

        HttpParams params = new HttpParams();

        RxVolley.post(
                "http://api.gpslink.cn/api/Token?username="+BoDaoID+"&password=123456&grant_type=password&scope=single", params
                , new HttpCallback() {
                    @Override
                    public void onSuccess(String t) {
                        super.onSuccess(t);
                        if (t!=null){
                            token =gson.fromJson(t,VehicleToken.class);
                            SpUtils.putString("Token",token.getAccess_token(),BaseApplication.getContext());
                            getVehiclePoint(token.getAccess_token());
                        }
                    }
                    @Override
                    public void onFailure(int errorNo, String strMsg) {
                        super.onFailure(errorNo, strMsg);
                        //Log.e("xxx",strMsg);

                    }
                });

    }
   private void getVehiclePoint(String token){
    HttpParams params = new HttpParams();
       params.putHeaders("Authorization","bearer"+" "+token);
       RxVolley.get("http://api.gpslink.cn/api/Point/Last?cid="+BoDaoID, params, new HttpCallback() {
           @Override
           public void onSuccess(String t) {
               super.onSuccess(t);

               if (t!=null){

                   boDaoLocation = gson.fromJson(t,BoDaoLocation.class);
                   bodaolatLng = GpsCorrect.transform(Double.valueOf(boDaoLocation.getLat()),Double.valueOf(boDaoLocation.getLng()));
                   showVehicle(bodaolatLng);
                   showVehicleLocation(bodaolatLng);
                   getLocationMsg();
               }
           }
           @Override
           public void onFailure(int errorNo, String strMsg) {
               super.onFailure(errorNo, strMsg);

           }
       });

   }
    private void getLocationMsg(){
        GeocodeSearch geocodeSearch = new GeocodeSearch(getActivity());
        LatLonPoint latLonPoint =new LatLonPoint(bodaolatLng.latitude,bodaolatLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint,10,GeocodeSearch.AMAP);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i==1000){
                    vehicleMsg.setText(regeocodeResult.getRegeocodeAddress().getFormatAddress());
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
geocodeSearch.getFromLocationAsyn(query);
    }
}
